//
//  ZhiFuViewController.m
//  JiuJiuShangCheng
//
//  Created by jiujiukeji on 2018/7/17.
//  Copyright © 2018年 jiujiukeji. All rights reserved.
//

#import "ZhiFuViewController.h"
#import "IDNWxPayer.h"
#import "WXApi.h"
#import "SettingSafeCodeViewController.h"
#import "ChangeSafeCodeViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "OrderViewController.h"
#import "GoodsDetailViewController.h"

@interface ZhiFuViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSDictionary *personalInfoDic;

@end

@implementation ZhiFuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColorWhite;
    [self loadBaseTitleLable:@"在线支付"];
    [self.view addSubview:self.tableView];
    
    [self getPersonalInfo];
    if (self.tiaoZhuanType == 1) {
        // 订单详情进入
        // 关闭右滑返回
        id traget = self.navigationController.interactivePopGestureRecognizer.delegate;
        UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:traget action:nil];
        [self.view addGestureRecognizer:pan];
        self.leftBtn.hidden = YES;
        self.SLeftBtn.hidden = NO;
        [self.SLeftBtn addTarget:self action:@selector(newBack) forControlEvents:(UIControlEventTouchUpInside)];
    }
}
- (void)newBack
{
    [self.navigationController popToRootViewControllerAnimated:YES];
//    for (UIViewController *controller in self.navigationController.viewControllers) {
//
//        if ([controller isKindOfClass:[GoodsDetailViewController class]]) {
//
//            GoodsDetailViewController *vc = (GoodsDetailViewController *)controller;
//            [self.navigationController popToViewController:vc animated:YES];
//        }
//    }
}
#pragma mark - 获取个人信息
- (void)getPersonalInfo
{
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/member.ashx?action=memberinfo&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:nil success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        
        if ([responseObject[@"status"] intValue] == 1) {
            self.personalInfoDic = responseObject;
            
        } else {
            [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
        }
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        
    }];
}
#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([self.payType isEqualToString:@"微信支付"] || [self.payType isEqualToString:@"支付宝"]) {
        return 3;
    } else {
        return 5;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = globalGray;
    [cell.contentView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(cell.contentView);
        make.height.equalTo(@(rateHeight(1)));
    }];
    if (indexPath.row == 4) {
        UITextField *textField = [[UITextField alloc] init];
        textField.textColor = UIColorFromRGB(0x333333);
        textField.placeholder = @"请输入安全密码";
        textField.font = UIFontSystem(14);
        [cell.contentView addSubview:textField];
        [textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(cell.contentView).offset(rateWidth(25));
            make.top.equalTo(cell.contentView).offset(rateHeight(10));
            make.size.mas_offset(CGSizeMake(rateWidth(700), rateHeight(60)));
        }];
        UILabel *label = [UILabel labelWithText:@"注：您未设置安全密码，请输入登录密码或" textColor:UIColorFromRGB(0x333333) fontSize:13];
        [label sizeToFit];
        [cell.contentView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(textField.mas_bottom);
            make.left.equalTo(textField);
        }];
        UILabel *label1 = [UILabel labelWithText:@"设置安全密码" textColor:UIColorFromRGB(0x333333) fontSize:13];
        label1.font = [UIFont boldSystemFontOfSize:13];
        [label1 sizeToFit];
        [cell.contentView addSubview:label1];
        [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(label);
            make.left.equalTo(label.mas_right);
        }];
        label1.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(setSafeCodeAction)];
        [label1 addGestureRecognizer:tap];
        
    } else {
        
        NSArray *array = @[[NSString stringWithFormat:@"订单编号：%@",self.orderNumber],[NSString stringWithFormat:@"应付总额：%@",self.payMoney],[NSString stringWithFormat:@"支付方式：%@",self.payType],@"您的余额：￥0.00"];
        UILabel *label = [UILabel labelWithText:array[indexPath.row] textColor:UIColorFromRGB(0x333333) fontSize:15];
        [label sizeToFit];
        [cell.contentView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(cell.contentView);
            make.left.equalTo(cell.contentView).offset(rateWidth(25));
        }];
    }
    cell.selectionStyle = NO;
    return cell;
}
#pragma mark - 设置安全密码
- (void)setSafeCodeAction
{
    // 安全密码
    if ([self.personalInfoDic[@"buyPassSet"] intValue] == 0) {
        // 设置安全密码
        SettingSafeCodeViewController *settingSafeCodeVC = [[SettingSafeCodeViewController alloc] init];
        [self.navigationController pushViewController:settingSafeCodeVC animated:YES];
    } else if ([self.personalInfoDic[@"buyPassSet"] intValue] == 1) {
        // 修改安全密码
        ChangeSafeCodeViewController *changeSafeCodeVC = [[ChangeSafeCodeViewController alloc] init];
        [self.navigationController pushViewController:changeSafeCodeVC animated:YES];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 4) {
        return rateHeight(150);
    } else {
        return rateHeight(90);
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return rateHeight(200);
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *bgV = [[UIView alloc] init];
    bgV.backgroundColor = UIColorWhite;
    UIButton *btn = [UIButton buttonWithTitle:@"立即支付" fontSize:15 titleColor:UIColorWhite background:navBarColor cornerRadius:6];
    [bgV addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_offset(CGSizeMake(rateWidth(600), rateHeight(80)));
        make.center.equalTo(bgV);
    }];
    [btn addTarget:self action:@selector(startPay) forControlEvents:(UIControlEventTouchUpInside)];
    
    return bgV;
}
#pragma mark - 发起支付
- (void)startPay
{
    if ([self.payType isEqualToString:@"微信支付"]) {
        [self wxPay];
    } else if ([self.payType isEqualToString:@"支付宝"]) {
        [self zhiFuBaoPay];
    }
}
#pragma mark - 支付宝支付
- (void)zhiFuBaoPay
{
    if (self.orderNumber) {
        NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
        [MBProgressHUD showMessage:nil toView:self.view];
        [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/shop/shop.ashx?action=ailpayapppay&companyid=%@&code=%@&timestamp=%@&ordernumber=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],self.orderNumber] parameters:nil success:^(id responseObject) {
            [MBProgressHUD hideHUDForView:self.view];
            
            if ([responseObject[@"status"] intValue] == 1) {
                // 发起支付宝支付
                [[AlipaySDK defaultService] payOrder:responseObject[@"paySign"] fromScheme:@"jiujiushangcheng" callback:^(NSDictionary *resultDic) {
                    
                    NSLog(@"支付宝支付返回：%@", resultDic);
                    if ([resultDic[@"resultStatus"] intValue] == 9000) {
                        [TFHUD addRemindHUD:self.view message:@"支付成功"];
                        // 支付成功
                        OrderViewController *orderVC = [[OrderViewController alloc] init];
                        orderVC.selectIndex1 = 2;
                        [self.navigationController pushViewController:orderVC animated:YES];
                        
                    } else {
                        [TFHUD addRemindHUD:self.view message:@"支付失败"];
                        // 待付款
                        OrderViewController *orderVC = [[OrderViewController alloc] init];
                        orderVC.selectIndex1 = 1;
                        [self.navigationController pushViewController:orderVC animated:YES];
                    }
                }];
            } else {
                [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
            }
            
        } failure:^(NSError *error) {
            [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
            
        }];
    }
}
#pragma mark - 微信支付
- (void)wxPay
{
    if (self.orderNumber) {
        NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
        [MBProgressHUD showMessage:nil toView:self.view];
        [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/shop/shop.ashx?action=weixinapppay&companyid=%@&code=%@&timestamp=%@&ordernumber=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],self.orderNumber] parameters:nil success:^(id responseObject) {
            [MBProgressHUD hideHUDForView:self.view];
            
            if ([responseObject[@"status"] intValue] == 1) {
                NSMutableDictionary *payParams = [NSMutableDictionary dictionary];
                [payParams setValue:responseObject[@"appid"] forKey:@"appid"];
                [payParams setValue:responseObject[@"paySign"] forKey:@"sign"];
                [payParams setValue:responseObject[@"nonceStr"] forKey:@"noncestr"];
                [payParams setValue:[NSString stringWithFormat:@"%@",responseObject[@"timeStamp"]] forKey:@"timestamp"];
                [payParams setValue:@"Sign=WXPay" forKey:@"package"];
                [payParams setValue:[NSString stringWithFormat:@"%@",responseObject[@"partnerid"]] forKey:@"partnerid"];
                [payParams setValue:responseObject[@"prepayid"] forKey:@"prepayid"];
                [self actionPayWithPayParams:payParams];
            } else {
                [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
            }
            
        } failure:^(NSError *error) {
            [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
            
        }];
    }
}
- (void)actionPayWithPayParams:(NSDictionary *)payParams
{
    // 发起支付
    BOOL isWxOpened = [IDNWxPayer payWithParams:payParams result:^(NSError *error) {
        if (error) {
            NSLog(@"支付失败：%@", error);
            [self alert:[NSString stringWithFormat:@"支付失败：%@", error.localizedDescription]];
        } else {
            NSLog(@"支付成功（只是“支付”成功）")       ;
            [self.navigationController popViewControllerAnimated:YES];
            [TFHUD addRemindHUD:self.view message:@"支付成功"];
            // 支付成功
            OrderViewController *orderVC = [[OrderViewController alloc] init];
            orderVC.selectIndex1 = 2;
            [self.navigationController pushViewController:orderVC animated:YES];
        }
    }];
    
    if(isWxOpened)
        ; //这里应该显示一个界面来询问支付是否成功（具体做法参考 IDNWxPayer.h 中的函数文档）
}
- (void)alert:(NSString*)msg
{
    UIAlertController* c = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* a = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 待付款
        OrderViewController *orderVC = [[OrderViewController alloc] init];
        orderVC.selectIndex1 = 1;
        [self.navigationController pushViewController:orderVC animated:YES];
    }];
    [c addAction:a];
    [self presentViewController:c animated:YES completion:nil];
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, kScreenWidth, kScreenHeight-SafeAreaTopHeight) style:(UITableViewStyleGrouped)];
        _tableView.backgroundColor = UIColorWhite;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
